package cn.aitrox.ry.service.config.controller;

import cn.aitrox.ry.bean.CommonPageInfo;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.service.config.api.ToolApi;
import cn.aitrox.ry.service.config.dto.ToolDto;
import cn.aitrox.ry.service.config.dto.in.ToolSearchInDto;
import cn.aitrox.ry.service.config.dto.in.ToolUpdateInDto;
import cn.aitrox.ry.service.config.entity.ToolEntity;
import cn.aitrox.ry.service.config.service.ToolService;
import cn.aitrox.ry.util.ArrayUtil;
import cn.aitrox.ry.util.BeanUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ToolController implements ToolApi {

    @Autowired
    private ToolService toolService;

    @PostMapping(value = "/config/tool/search")
    @Override
    public CommonPageInfo<ToolDto> toolSearch(@RequestBody ToolSearchInDto input) {
        PageInfo<ToolEntity> pageInfo = toolService.search(input.getPage(), input.getPageSize(), input.getName(), input.getValueList());
        if (ArrayUtil.isEmpty(pageInfo.getList())) {
            return new CommonPageInfo(0, 0, null);
        }
        List<ToolDto> list = pageInfo.getList().stream().map(x -> {
            ToolDto tool = new ToolDto();
            BeanUtil.copy(x, tool);
            return tool;
        }).collect(Collectors.toList());
        return new CommonPageInfo(pageInfo.getTotal(), pageInfo.getPages(), list);
    }

    @PutMapping(value = "/config/tool")
    @Override
    public RespResult edit(@Validated @RequestBody ToolUpdateInDto input) {
        return toolService.edit(input.getId(), input.getName(), input.getRemark());
    }

    @GetMapping(value = "/config/tool/maxCode")
    @Override
    public String maxCode() {
        return toolService.maxValue();
    }
}
